package fun.rockchen.service.concreteService;

import fun.rockchen.bean.Tag;
import fun.rockchen.dao.TagDao;
import fun.rockchen.service.interfaceService.TagService;
import fun.rockchen.utils.responseUtils.ResponseJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Objects;

/**
 * @author Rock Chen
 * @Description:
 * @date 2023/10/16 10:22
 */

@Service
public class TagServiceImpl implements TagService {
    private final TagDao tagDao;

    @Autowired
    public TagServiceImpl(TagDao tagDao) {
        this.tagDao = tagDao;
    }

    @Override
    public ResponseEntity<?> getTagList(Tag tag) {
        try {
            List<Tag> tagEntity = tagDao.getTagList(tag);
            if (tagEntity != null) {
                return ResponseEntity.ok().body(ResponseJson.getSuccess(tagEntity));
            } else {
                return ResponseEntity.ok().body(ResponseJson.NoData());
            }
        } catch (Exception e) {
            return ResponseEntity.status(4987).body(ResponseJson.getError());
        }
    }
    
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackForClassName = "Exception")
    public ResponseEntity<?> deleteTag(String tagId) {
        try {
            if (Objects.equals(tagId, "")) {
                return ResponseEntity.status(400).body(ResponseJson.fail());
            } else {
                boolean flag = tagDao.deleteTag(tagId);
                if (flag) {
                    return ResponseEntity.ok(ResponseJson.deleteSuccess());
                }
                return ResponseEntity.status(488).body(ResponseJson.deleteFail());
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseEntity.status(488).body(ResponseJson.deleteFail());
        }

    }
}
